from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import ServiceProvider, Service, Rating, Carousel
from app import db
from app.schemas import (
    ServiceProviderSchema, 
    ServiceSchema,
    RatingSchema,
    CarouselSchema
)

bp = Blueprint('api', __name__, url_prefix='/api')

# 服务提供者管理
@bp.route('/providers', methods=['GET'])
def get_providers():
    providers = ServiceProvider.query.all()
    return jsonify({
        'status': 'success',
        'data': ServiceProviderSchema(many=True).dump(providers)
    })

@bp.route('/providers', methods=['POST'])
@jwt_required()
def create_provider():
    try:
        data = request.get_json()
        provider = ServiceProvider(
            name=data['name'],
            description=data.get('description', ''),
            category_id=data['category_id']
        )
        db.session.add(provider)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Provider created successfully',
            'data': ServiceProviderSchema().dump(provider)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/providers/<int:id>', methods=['PUT'])
@jwt_required()
def update_provider(id):
    try:
        provider = ServiceProvider.query.get_or_404(id)
        data = request.get_json()
        
        if 'name' in data:
            provider.name = data['name']
        if 'description' in data:
            provider.description = data['description']
        if 'category_id' in data:
            provider.category_id = data['category_id']
            
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Provider updated successfully',
            'data': ServiceProviderSchema().dump(provider)
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/providers/<int:id>', methods=['DELETE'])
@jwt_required()
def delete_provider(id):
    try:
        provider = ServiceProvider.query.get_or_404(id)
        db.session.delete(provider)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Provider deleted successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# 服务管理
@bp.route('/services', methods=['GET'])
def get_services():
    services = Service.query.all()
    return jsonify({
        'status': 'success',
        'data': ServiceSchema(many=True).dump(services)
    })

@bp.route('/services', methods=['POST'])
@jwt_required()
def create_service():
    try:
        data = request.get_json()
        service = Service(
            title=data['title'],
            description=data.get('description', ''),
            provider_id=data['provider_id'],
            category_id=data['category_id'],
            image_url=data.get('image_url'),
            video_url=data.get('video_url'),
            audio_url=data.get('audio_url')
        )
        db.session.add(service)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Service created successfully',
            'data': ServiceSchema().dump(service)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/services/<int:id>', methods=['PUT'])
@jwt_required()
def update_service(id):
    try:
        service = Service.query.get_or_404(id)
        data = request.get_json()
        
        for field in ['title', 'description', 'provider_id', 'category_id', 
                     'image_url', 'video_url', 'audio_url']:
            if field in data:
                setattr(service, field, data[field])
                
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Service updated successfully',
            'data': ServiceSchema().dump(service)
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/services/<int:id>', methods=['DELETE'])
@jwt_required()
def delete_service(id):
    try:
        service = Service.query.get_or_404(id)
        db.session.delete(service)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Service deleted successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# 评价管理
@bp.route('/ratings', methods=['GET'])
def get_ratings():
    ratings = Rating.query.all()
    return jsonify({
        'status': 'success',
        'data': RatingSchema(many=True).dump(ratings)
    })

@bp.route('/ratings', methods=['POST'])
@jwt_required()
def create_rating():
    try:
        data = request.get_json()
        rating = Rating(
            provider_id=data['provider_id'],
            user_id=get_jwt_identity(),
            rating=data['rating'],
            comment=data.get('comment', '')
        )
        db.session.add(rating)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Rating created successfully',
            'data': RatingSchema().dump(rating)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/ratings/<int:id>', methods=['DELETE'])
@jwt_required()
def delete_rating(id):
    try:
        rating = Rating.query.get_or_404(id)
        if rating.user_id != get_jwt_identity():
            return jsonify({
                'status': 'error',
                'message': 'Not authorized'
            }), 403
        db.session.delete(rating)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Rating deleted successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# 轮播图管理
@bp.route('/carousel', methods=['GET'])
def get_carousel():
    carousel_items = Carousel.query.all()
    return jsonify({
        'status': 'success',
        'data': CarouselSchema(many=True).dump(carousel_items)
    })

@bp.route('/carousel', methods=['POST'])
@jwt_required()
def create_carousel():
    try:
        data = request.get_json()
        carousel = Carousel(
            image_url=data['image_url'],
            link=data.get('link')
        )
        db.session.add(carousel)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Carousel item created successfully',
            'data': CarouselSchema().dump(carousel)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/carousel/<int:id>', methods=['DELETE'])
@jwt_required()
def delete_carousel(id):
    try:
        carousel = Carousel.query.get_or_404(id)
        db.session.delete(carousel)
        db.session.commit()
        return jsonify({
            'status': 'success',
            'message': 'Carousel item deleted successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 